package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
    private static Connection con;
    private static String url;
    private static String user;
    private static String pwd;
    private DBUtil() {   }
    static {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            InputStream is=DBUtil.class.getResourceAsStream("/db.properties");
            Properties prop=new Properties();
            prop.load(is);
            url=prop.getProperty("url");
            user=prop.getProperty("user");
            pwd=prop.getProperty("password");
            System.out.println(url+"  "+user+"  "+pwd);
            con= DriverManager.getConnection(url,user,pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static ResultSet find(String sql){
        con=getCon();
        try {
            Statement stm=con.createStatement();
            ResultSet rs=stm.executeQuery(sql);
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static ResultSet find(String sql,Object ...param){
        con=getCon();
        try {
            PreparedStatement pstm=con.prepareStatement(sql);
            for(int i=0;i<param.length;i++){
                pstm.setObject(i+1,param[i]);
            }
            ResultSet rs=pstm.executeQuery();
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static void insert(String sql,Object...param){
        con=getCon();
        try {
            PreparedStatement pstm=con.prepareStatement(sql);
            for (int i=0;i<param.length;i++){
                pstm.setObject(i+1,param[i]);
            }
               pstm.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static Connection getCon(){
        try {
            if(con==null||con.isClosed())
                con= DriverManager.getConnection(url,user,pwd);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
}
